import os


def file_to_list(file_path):
    """【函数】将文件内容转换为列表"""
    content_list = list()
    with open(file_path, "r", encoding="utf-8") as file_obj:
        for line in file_obj.readlines():
            line_content = str(line).split("\n")[0]
            content_list.append(line_content)
    return content_list


def list_to_file(content_list, file_path):
    """【函数】将列表内容转换为文件"""
    with open(file_path, "w+", encoding="utf-8") as file_obj:
        for content in content_list:
            file_obj.write(str(content) + "\n")
    print("Successfully save to file:", file_path.split("/")[-1])
    return None


def piplist_to_file(file_path, ifshow=False):
    """【函数】将 pip list 保存为文本文件"""
    os.system("pip freeze > " + file_path)
    packages_list = file_to_list(file_path)
    with open(file_path, "w+", encoding="utf-8") as packages_file:
        for package in packages_list:
            packages_file.write(str(package.split("=")[0].split(" ")[0]) + "\n")
    __show_list(ifshow)
    return None


def install_packages(package_names, ifshow=False):
    """【函数】批量安装"""
    for package_name in package_names:
        os.system("pip install " + package_name)
    __show_list(ifshow)
    return None


def uninstall_packages(packages_list, ifshow=False):
    """【函数】批量卸载"""
    for package in packages_list:
        os.system("pip uninstall " + package + " -y")
    __show_list(ifshow)
    return None


def ungrade_packages(packages_list, ifshow=False):
    """【函数】批量更新"""
    for package in packages_list:
        os.system("pip install --upgrade " + package)
    __show_list(ifshow)
    return None


def __show_list(ifshow):
    if (ifshow==True):
        os.system("pip list")
    print("全部完成！")
    return None


def xxx(file_path, except_items=None, show=False):
    # 任务代码
    packages_list = file_to_list(file_path)
    for except_item in except_items:
        packages_list.remove(except_item)
    # uninstall_packages(packages_list)
    # ungrade_packages(packages_list)


def apply_setenv(ini_list):
    """【应用场景】清理并按照特定清单配置环境"""
    # 清  理
    piplist_to_file("clean_list.txt", True)
    uninstall_packages(file_to_list("clean_list.txt"))
    # 安  装
    install_packages(file_to_list(ini_list), True)
    # 更  新
    piplist_to_file("upgrade_list.txt")
    ungrade_packages(file_to_list("upgrade_list.txt"))
    return None


if (__name__ == "__main__"):

    apply_setenv("pip_list-data_analysis.txt")
